﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Navigate;
using System.Collections.ObjectModel;

namespace G.Reader.View
{
    public class ChatUtil
    {
        public string From { get; set; }

        public string Message { get; set; }
    }

    public partial class ChatPage : GBasePage
    {
        PushService.PushServiceClient client = new PushService.PushServiceClient();
        UserInfoService.UserInfoServiceClient userinfoServiceClient = new UserInfoService.UserInfoServiceClient();

        ObservableCollection<ChatUtil> chats = new ObservableCollection<ChatUtil>();
        public ChatPage()
        {
            InitializeComponent();
            this.listChat.ItemsSource = chats;
            Utils.PushHelp.RecivedRaw += new Utils.ReciveRawHandel(PushHelp_RecivedRaw);
            userinfoServiceClient.GetUserInfosByIdsCompleted += new EventHandler<UserInfoService.GetUserInfosByIdsCompletedEventArgs>(userinfoServiceClient_GetUserInfosByIdsCompleted);
        }

        void PushHelp_RecivedRaw(object obj, Utils.ReciveRawArgs e)
        {
            string str = e.Messasge;
            int offset = str.IndexOf(':');
            ChatUtil c = new ChatUtil();
            c.From = str.Substring(0, offset);
            c.Message = str.Substring(offset + 1);
            this.Dispatcher.BeginInvoke(() =>
            {
                chats.Add(c);
                this.listChat.ScrollIntoView(c);
            });
        }

        void userinfoServiceClient_GetUserInfosByIdsCompleted(object sender, UserInfoService.GetUserInfosByIdsCompletedEventArgs e)
        {
            list_friends.ItemsSource = e.Result;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (list_friends.ItemsSource == null)
            {
                client.GetPushsCompleted += new EventHandler<PushService.GetPushsCompletedEventArgs>(client_GetPushsCompleted);
                client.GetPushsAsync();
            }

        }
        ObservableCollection<PushService.PushInfo> PushInfos;
        void client_GetPushsCompleted(object sender, PushService.GetPushsCompletedEventArgs e)
        {
            //list_friends.ItemsSource = e.Result;
            if (e.Error == null)
            {
                PushInfos = e.Result;
                ObservableCollection<int> ids = new ObservableCollection<int>();
                foreach (var item in e.Result)
                {
                    if (item.UserId.HasValue )//&& item.UserId.Value != GloabalData.Instance.User.Id)
                        ids.Add(item.UserId.Value);
                }
                userinfoServiceClient.GetUserInfosByIdsAsync(ids);
            }
        }

        private PushService.PushInfo CurrentSelectedPushInfo;
        private void list_friends_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (list_friends.SelectedItem != null)
            {
                UserInfoService.UserInfo userinfo = list_friends.SelectedItem as UserInfoService.UserInfo;
                CurrentSelectedPushInfo = PushInfos.FirstOrDefault(c => c.UserId == userinfo.Id);
                //client.PushMessage_WP7_RawAsync(pushinfo.PushAddress, "dasdasd", new Dictionary<string, string>());
                //client.PushMessageAsync(pushinfo.PushAddress, "你好", PushService.PushType.Toast);
            }
            //client.PushMessageAsync(
        }

        private void txtSend_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.Focus();
                if (CurrentSelectedPushInfo == null)
                {
                    MessageBox.Show("请选择一个好友进行聊天");
                    return;
                }
                if (!string.IsNullOrEmpty(txtSend.Text))
                {
                    string str = string.Format("{0}:{1}", GloabalData.Instance.User.NickName, txtSend.Text);
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
                    if (str.Length > 1024)
                    {
                        MessageBox.Show("消息长度超过最大允许长度");
                        return;
                    }
                    ChatUtil c = new ChatUtil() { From = GloabalData.Instance.User.NickName, Message = txtSend.Text };
                    this.chats.Add(c);
                    client.PushMessage_WP7_RawAsync(CurrentSelectedPushInfo.PushAddress, buffer, new Dictionary<string, string>());
                    this.txtSend.Text = "";
                }
            }
        }
    }
}